package cn.cjlmonster.hyouka_assistant.utils

import java.net.URLEncoder

object UrlBuilder {

    /**
     * 构建带参数的URL
     */
    fun buildUrlWithParams(baseUrl: String, params: Map<*, *>? = null): String {
        if (params.isNullOrEmpty()) return baseUrl

        val urlBuilder = StringBuilder(baseUrl)

        if (!baseUrl.contains("?")) {
            urlBuilder.append("?")
        } else if (!baseUrl.endsWith("&") && !baseUrl.endsWith("?")) {
            urlBuilder.append("&")
        }

        val encodedParams = params.map { (key, value) ->
            "${URLEncoder.encode(key.toString(), "UTF-8")}=${
                URLEncoder.encode(
                    value.toString(),
                    "UTF-8"
                )
            }"
        }.joinToString("&")

        urlBuilder.append(encodedParams)

        return urlBuilder.toString()
    }
}
